<template>
  <div class="commwaik-bk">
    <!-- 小图内容 -->
    <div class="comwaik-xiaoimg">
      <div class="image-list">
        <ul>
          <li v-for="(image, index) in product.images" :key="index" @mouseover="showImage(image)">
            <img :src="`/${image}`" :alt="'Image ' + (index + 1)" style="border-radius: 10px"/>
          </li>
        </ul>
      </div>
    </div>

    <!-- 大图内容 -->
    <div class="commwaik-img">
      <img :src="`/${currentImage}`" alt="Large Image" style="width: 100%;height: 100%;border-radius: 20px"/>
    </div>

    <div class="commwaik-font">
      <div class="product-detail">
        <!-- 商品标题和价格 -->
        <div class="product-header">
          <h1>{{ product.title }}{{product.descrip}}</h1>
          <div class="price">
            <span class="current-price">￥{{ product.currentPrice }}</span>
            <span class="original-price">优惠前￥{{ product.originalPrice }}</span>
            <span class="sales-count">已售 {{ product.salesCount }}+</span>
          </div>
        </div>

        <!-- 配送和保障 -->
        <div class="product-info">
          <div style="color: #666666">
            <strong>配&nbsp;送：</strong>
            <p style="margin-left: 66px;margin-bottom: 20px">{{ product.deliveryInfo_cc }}</p>
          </div>
          <div style="color: #666666">
            <strong>保&nbsp;障：</strong>
            {{ product.guaranteeInfo }}
          </div>
        </div>

        <!-- 选择 -->
        <div class="product-options">
          <!-- 选择配置 -->
          <div class="option">
            <strong style="color: #333;">选择：</strong>
            <button
                v-for="(color, index) in product.colorOptions"
                :key="index"
                :class="{ active: selectedColor === color }"
                @click="selectColor(color)"
            >
              {{ color }}
            </button>
          </div>

          <!-- 数量选择 -->
          <div class="quantity">
            <strong style="color: #333;">数量：</strong>
            <button @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
            <input type="text" v-model="quantity" />
            <button @click="increaseQuantity">+</button>
            <span class="stock-status">{{ product.stockStatus }}</span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="product-actions">
          <button class="buy-now" @click="goOrders">立即购买</button>
          <button class="add-to-cart">加入购物车</button>
          <button class="save">收藏</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import "./Subject.css";
import { ref, onMounted } from "vue";
import axios from "axios";
import { useRoute } from "vue-router";
import router from "@/router/index.js";

// 获取路由参数
const route = useRoute();
const productId = ref(route.params.id); // 获取商品 id

// 初始化商品数据
const product = ref({
  title: "",
  descrip: "",
  currentPrice: 0,
  originalPrice: 0,
  salesCount: 0,
  deliveryInfo_cc: "",
  guaranteeInfo: "",
  colorOptions: [],
  stockStatus: "",
  images: [],
});

// 当前选中状态
const selectedColor = ref(null);
const quantity = ref(1); // 默认数量

// 当前显示的大图
const currentImage = ref(null);

// 获取商品数据的函数
const fetchProductData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/home/Indivi', {
      params: { productId: productId.value },
    });

    if (response.data.status === 200) {
      const data = response.data.data;
      product.value = {
        title: data.productname,
        descrip: data.description,
        currentPrice: parseFloat(data.price),
        originalPrice: parseFloat(data.preferential),
        salesCount: data.sold,
        deliveryInfo_cc: data.distribution,
        guaranteeInfo: data.guarantee,
        colorOptions: data.parameters.map(param => param.parameter_value),
        stockStatus: data.stock > 0 ? "有货" : "缺货",
        images: data.images.map(img => img.imageurl), // 直接使用文件名
        merchantid:data.merchantid
      };
      console.log('商品所有数据:', product.value);
      currentImage.value = product.value.images[0]; // 设置默认大图
      selectedColor.value = product.value.colorOptions[0]; // 设置默认颜色
      console.log("默认选中的颜色:", selectedColor.value); // 输出默认选中的颜色
    } else {
      console.error("获取商品数据失败:", response.data.message);
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

// 方法：选择颜色
const selectColor = (color) => {
  selectedColor.value = color;
  console.log("当前选中的颜色:", selectedColor.value);
};

// 方法：增加/减少数量
const increaseQuantity = () => {
  quantity.value++;
};

const decreaseQuantity = () => {
  if (quantity.value > 1) quantity.value--;
};

// 鼠标悬停时切换大图
const showImage = (image) => {
  currentImage.value = image;
};

// 页面加载时获取商品数据
onMounted(() => {
  fetchProductData();
});

// 点击立即购买
// 点击立即购买
const goOrders = () => {
  // 计算总价
  const totalPrice = (product.value.currentPrice * quantity.value).toFixed(2);

  const user = JSON.parse(localStorage.getItem('user'));
  const userId = user.userid;

  // 构建订单数据
  const orderData = {
    userid: userId,                        // 用户ID
    productid: productId.value,            // 商品ID
    parametername: selectedColor.value,    // 选择的颜色
    totalprice: totalPrice,                // 总价格
    merchantid: product.value.merchantid  // 传递商家ID
  };

  // 使用 params 传递动态路由参数
  const orderParams = {
    id: productId.value,
    name: product.value.title,
    price: product.value.currentPrice,
    quantity: quantity.value,
    image: currentImage.value,
    selectedColor: selectedColor.value,
    orderData: orderData,  // 把订单数据作为参数传递
  };

  // 打印路由参数
  console.log("路由参数:", orderParams);

  // 跳转到订单页面
  router.push({
    name: 'orders',   // 目标路由
    params: orderParams, // 动态路由参数
  });
};
</script>
